<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="talk" placeholder="请输入内容与机器人聊天，回车提交" />
    <div id="result"></div>
    <script>
      // http://ajax-api.itheima.net/api/robot GET
      const talk = document.querySelector("#talk");
      const result = document.querySelector("#result");
      // DOM0 直接绑，DOM2 addEventListener
      talk.onkeyup = (e) => {
        if (e.key === "Enter") {
          // 按下回车的时候，发送请求
          fetch("http://ajax-api.itheima.net/api/robot?spoken=" + talk.value, {
            method: "GET",
            // 关注下面的 .then 等待一段时间后
          })
            .then((res) => res.json())
            .then((res) => {
              // success
              console.log(res?.data?.info?.text);
              result.innerHTML += `<div>机器人：${res.data.info.text}</div>`;
            });

          // 记录我说的话
          result.innerHTML += `<div>我：${talk.value}</div>`;

          // 清空聊天
          talk.value = null;
          //   const xhr = new XMLHttpRequest();
          //   xhr.open(
          //     "GET",
          //     "http://ajax-api.itheima.net/api/robot?spoken=" + talk.value
          //   );
          //   xhr.send();
          //   xhr.responseType = "json";
          //   xhr.onreadystatechange = () => {
          //     if (xhr.readyState === 4 && xhr.status === 200) {
          //       // success
          //       console.log(xhr.response.data.info.text);
          //       result.innerHTML += `<div>机器人：${xhr.response.data.info.text}</div>`;
          //     }
          //   };
        }
      };
    </script>
  </body>
</html>
